#include"CCServerContraller.h"
bool CCserverContraller::m_bServerRunning = true;

CCserverContraller::CCserverContraller(){
    printf("CCserverContraller构造\n");
    initVideoCapture();
    m_bServerRunning = true;
    m_TcpServer = new CCStreamServer();
    
    

    signal(SIGINT,exitServerSignalEmit);
    
}
CCserverContraller::~CCserverContraller(){
    if(m_TcpServer!=NULL){
        delete m_TcpServer;
    }

    unInitVideoVapture();
}

void CCserverContraller::startCapturevideo(){
    detach_thread_creat(NULL,(void*)startCaptureDetach,(void *)this);

    m_TcpServer->StartTCPServer();
}

void CCserverContraller::startCaptureDetach(long long num){
    printf("startCaptureDetach\n");
    CCserverContraller* Capture = (CCserverContraller*)num;
    if(Capture==NULL){
        printf("Capture is NULL");
    }
    Capture->RunVideoCapture();
}
void CCserverContraller::RunVideoCapture(){
    

    while(m_bServerRunning){
        
        int readFrame = read_and_encode_frame(m_cam);
        //printf("readFrame:%d\n",readFrame);
        if(readFrame==0){
            if(m_cam->encodedLength>0){
                m_TcpServer->SendAVStream(m_cam->h264_buf,m_cam->encodedLength,CONTEXT_AVSTREAM_VIDEO);;
                
            }
            
        }
        //usleep(10*1000);
    }
    //printf("m_TcpServer->xExit();");
    m_TcpServer->xExit();
}
void CCserverContraller::initVideoCapture(){
    m_cam = (IOTC_Camera*)malloc(sizeof(IOTC_Camera));
    if(m_cam==NULL){
        printf("malloc IOTC_Camera failed");
        return;
    }

    m_cam->device_name = (char*)"/dev/video0";
    m_cam->buffers = NULL;
    m_cam->width = 720;
    m_cam->height = 480;
    m_cam->display_depth = 5;
    camera_open(m_cam);
    camera_init(m_cam);
    camera_capturing_start(m_cam);

    h264_encoder_init(&m_cam->encoder,m_cam->width,m_cam->height);
    m_cam->h264_buf = (uint8_t*)malloc(sizeof(uint8_t)*m_cam->width*m_cam->height*3);//RGB格式每个像素用三字节存放
}

void CCserverContraller::exitServerSignalEmit(int num){
    //printf("exitServerSignalEmit\n");
    m_bServerRunning = false;
}
void CCserverContraller::unInitVideoVapture(){
    if(m_cam==NULL){
        return;
    }

    h264_encoder_uninit(&m_cam->encoder);
    camera_uninit(m_cam);
    camera_close(m_cam);

    free(m_cam);
}